package com.eselect.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 路由失败时调用
 */
@Component
@Slf4j
public class MQPublisherReturnHandler implements ApplicationContextAware {
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            int replyCode = returnedMessage.getReplyCode();
            String replyText = returnedMessage.getReplyText();
            String exchange = returnedMessage.getExchange();    // 异常的交换机
            String msg = new String(returnedMessage.getMessage().getBody());    // 异常的消息
            log.error("消息投递失败 ==》交换机：{}，消息：{}，错误码：{}，错误信息：{}", exchange, msg, replyCode, replyText);
        });
    }
}
